package com.kai.admin.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.kai.admin.enums.AdminErrorCodeConstants;
import com.kai.admin.exception.LoginException;
import com.kai.admin.security.provider.token.UsernameAuthenticationToken;
import com.kai.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 账号密码登录过滤器
 */
@Slf4j
public class UsernameAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";

    private static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

    public UsernameAuthenticationFilter(AntPathRequestMatcher antPathRequestMatcher) {
        super(antPathRequestMatcher);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        JSONObject bodyParameters = WebUtil.getBodyParameters(request);
        if (Objects.isNull(bodyParameters)) {
            throw new LoginException(AdminErrorCodeConstants.USERNAME_OR_PASSWORD_IS_NULL);
        }
        String username = bodyParameters.getString(SPRING_SECURITY_FORM_USERNAME_KEY);
        String password = bodyParameters.getString(SPRING_SECURITY_FORM_PASSWORD_KEY);

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new LoginException(AdminErrorCodeConstants.USERNAME_OR_PASSWORD_IS_NULL);
        }

        UsernameAuthenticationToken authRequest = new UsernameAuthenticationToken(username, password);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request, UsernameAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}